package com.guxuede.mina.mainserver;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.guxuede.mina.bean.HttpMessage;
import com.guxuede.mina.chat.ChatPro;
import com.guxuede.mina.util.FileUtil;


public class ServerHandler extends IoHandlerAdapter{

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		cause.printStackTrace();
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		System.out.println("Server：接受消息："+message);
		HttpMessage request=(HttpMessage)message;
		if(request.uri.endsWith("Hello.chat")){
			ChatPro.chatSessionReceived(request, session);
		}else{
			HttpMessage response=HttpMessage.getDefaultResponse();
			response.body=FileUtil.getFileIoBuffer(request.uri);
			session.write(response);
			session.close(true);
		}
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		System.out.println("Server：连接关闭");
		ChatPro.chatSessionLeave(session);
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status)throws Exception {

	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
	}
}
